//
//  MQVideoSocietyViewController.m
//  MQ
//
//  Created by lanou on 15/10/26.
//  Copyright © 2015年 徐永祥. All rights reserved.
//

#import "MQVideoSocietyViewController.h"
#import "PKRequestManager.h"
#import "MQSocietyBodyList.h"
#import "MQSocietyViewCell.h"
#import "MQCollectionHeaderView.h"
#import <UIImageView+WebCache.h>
#import "MQVideoSocietyDetailViewController.h"
#import <MJRefresh.h>
#import <FMDatabase.h>
#import "Reachability.h"
@interface MQVideoSocietyViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UIScrollViewDelegate>
@property (nonatomic, strong)NSMutableArray * dataArr;
@property (nonatomic, strong)NSMutableArray * headArr;
@property (nonatomic, strong)UICollectionView * collectionView;
@property (nonatomic, strong)UICollectionViewFlowLayout * layOut;
@property (nonatomic, strong)UIScrollView * scrollView;
@property (nonatomic, strong)MQCollectionHeaderView * headerView;
@property (nonatomic, copy)NSMutableString * positionId;
@property (nonatomic, strong)FMDatabase * db;
@property (nonatomic, strong)UIImageView * remindView;
@property (nonatomic, strong)UILabel * remindLabel;
@property (nonatomic, assign)BOOL isLoadNew;
@end

@implementation MQVideoSocietyViewController
//懒加载
-(NSMutableArray *)dataArr
{
    if (_dataArr == nil) {
        self.dataArr = [NSMutableArray arrayWithCapacity:0];
    }
    return _dataArr;
}
-(NSMutableArray *)headArr
{

    if (_headArr == nil) {
        self.headArr = [NSMutableArray arrayWithCapacity:0];
    }
    return _headArr;
    
}

//创建数据库
-(void)creatDataBase
{
    NSString *dbpath = [NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingString:@"society.db"];
    _db = [FMDatabase databaseWithPath:dbpath];
    NSLog(@"%@",dbpath);
    
    if([_db open])
    {
        NSString *sql = [NSString stringWithFormat:@"create table  MyTable (dataName text primary key, jsonData blob)"];
        BOOL rs = [_db executeUpdate:sql];
        if(!rs)
        {
            NSLog(@"error create table!");
        }else
        {
            NSLog(@"successed create table!");
            
        }
    }
    
    
}

//从数据库中取出数据
-(void)queryFormDataBase
{
    NSString *sql = @"select jsonData from MyTable where dataName = ?";
    FMResultSet * rs = [_db executeQuery:sql, @"society"];
    while ([rs next])
    {
        
        NSData *jsonData = [rs dataForColumnIndex:0];
        NSDictionary * dataDic = [NSJSONSerialization JSONObjectWithData:jsonData options:(NSJSONReadingMutableContainers) error:nil];
        NSArray * array = [dataDic objectForKey:@"bodyList"];
        for (NSDictionary * modelDic in array) {
            MQSocietyBodyList * model = [[MQSocietyBodyList alloc]init];
            [model setValuesForKeysWithDictionary:modelDic];
            [self.dataArr addObject:model];
        }
    }
    [rs close];
    
}


//请求数据
-(void)requestData
{

    if (self.positionId.length==0) {
        self.positionId = [NSMutableString stringWithFormat:@"%@",@"0"];
    }
    NSString * url = [NSString stringWithFormat:@"http://vcsp.ifeng.com/vcsp/appData/recommendGroupByTeamid.do?pageSize=20&adapterNo=6.9.2&isNotModified=0&useType=androidPhone&channelId=100413-0&positionId=%@",self.positionId];
    
    [PKRequestManager requestWithType:GET urlString:url parDic:nil finish:^(NSData *data) {
        [self creatDataBase];
        NSString *sql = [NSString stringWithFormat:@"insert into MyTable (dataName, jsonData) values (?, ?)"];
        [_db executeUpdate:sql, @"society", data];
        if(_isLoadNew==YES) {
            [self.dataArr removeAllObjects];
        }
        NSDictionary * dataDic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        NSArray * array = [dataDic objectForKey:@"bodyList"];
        for (NSDictionary * modelDic in array) {
            MQSocietyBodyList * model = [[MQSocietyBodyList alloc]init];
            [model setValuesForKeysWithDictionary:modelDic];
            [self.dataArr addObject:model];
        }
       
        NSArray * headerArr = [dataDic objectForKey:@"header"];
        
        for (NSDictionary * headDic in headerArr) {
            MQSocietyHeadModel * model = [[MQSocietyHeadModel alloc]init];
            [model setValuesForKeysWithDictionary:headDic];
            [self.headArr addObject:model];
            
        }
       
        [self.collectionView reloadData];
        [self.collectionView.header endRefreshing];
        [self.collectionView.footer endRefreshing];
        for (int i = 0; i<2; i++) {
            ((UIImageView *)_headerView.scrollView.subviews[i*2]).tag =100+i;
            ((UIImageView *)_headerView.scrollView.subviews[i*2]).userInteractionEnabled = YES;
            [((UIImageView *)_headerView.scrollView.subviews[i*2]) sd_setImageWithURL:[NSURL URLWithString:((MQSocietyHeadModel *)self.headArr[i]).image]];
            
            UITapGestureRecognizer * gesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapToNext:)];
            
            [((UIImageView *)_headerView.scrollView.subviews[i*2])  addGestureRecognizer:gesture];
            ((UILabel *)_headerView.scrollView.subviews[2*i+1]).text =((MQSocietyHeadModel *)self.headArr[i]).title;
        }
        [_headerView.pageControl addTarget:self action:@selector(changePicture) forControlEvents:(UIControlEventValueChanged)];
        _headerView.pageControl.currentPage = 0;
        _headerView.scrollView.delegate = self;
        [NSTimer scheduledTimerWithTimeInterval:4.0 target:self selector:@selector(scrollViewAnimation) userInfo:nil repeats:YES];
    } error:^(NSError *error) {
        NSLog(@"%@",error);
    }];
    
    

}
-(void)remindOfConnection
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:TITLE_MESSAGE preferredStyle:(UIAlertControllerStyleAlert)];
    
    [self presentViewController:alert animated:YES completion:nil];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [alert dismissViewControllerAnimated:YES completion:nil];
    });
    
}


//判断当前网络状态
-(BOOL) isConnectionAvailable{
    
    BOOL isExistenceNetwork = YES;
    Reachability * hostReach = [Reachability reachabilityWithHostName:@"www.apple.com"];
    switch ([hostReach currentReachabilityStatus]) {
        case NotReachable:
            isExistenceNetwork = NO;
            //            NSLog(@"notReachable");
            break;
        case ReachableViaWiFi:
            isExistenceNetwork = YES;
            //            NSLog(@"WIFI");
            break;
        case ReachableViaWWAN:
            isExistenceNetwork = YES;
            //            NSLog(@"3G");
            break;
    }
    return isExistenceNetwork;
}


//   点击imageView跳转页面
-(void)tapToNext:(UITapGestureRecognizer *)recognizer
{
    
    MQSocietyHeadModel * model = self.headArr[recognizer.view.tag-100];
    
    MQVideoSocietyDetailViewController * detailVC = [[MQVideoSocietyDetailViewController alloc]init];
    detailVC.guid = model.memberItem.guid;
    [self presentViewController:detailVC animated:YES completion:nil];
}

-(void)viewReLoad
{
    
    //配置collectionView
    _layOut = [[UICollectionViewFlowLayout alloc]init];
    _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0,0, screen_width, screen_height-110) collectionViewLayout:_layOut];
    _collectionView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_collectionView];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    [_collectionView registerClass:[MQSocietyViewCell class] forCellWithReuseIdentifier:@"cell"];
    
    
    //    设置layout
    _layOut.itemSize = CGSizeMake((screen_width-30)/2+5, 150);
    _layOut.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);
    _layOut.minimumInteritemSpacing = 5;
    _layOut.minimumLineSpacing = 5;
    
    //   注册一个头视图
    _headerView = [[MQCollectionHeaderView alloc]initWithFrame:CGRectMake(0, 0, screen_width, 120)];
    [self.collectionView registerClass:[MQCollectionHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
}




- (void)viewDidLoad {
    [super viewDidLoad];
    _positionId = [NSMutableString string];
    
    [self viewReLoad];
    
    if ([self isConnectionAvailable]) {
        
         [self requestData];
    }
    else
    {
        [self creatDataBase];
        [self queryFormDataBase];

    }
    
    self.collectionView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        if ([self isConnectionAvailable]) {
            [self.dataArr removeAllObjects];
            self.positionId=0;
            [self requestData];
        }
        else
        {
            _isLoadNew = YES;
            [self remindOfConnection];
            [self.collectionView.header endRefreshing];
        }
    }];
    
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeTbaleViewFrame) name:@"table" object:nil];
    
  }

-(void)changeTbaleViewFrame
{
    self.collectionView.frame =CGRectMake(0,60, screen_width, screen_height-100);

}

//实现自动轮滑
-(void)scrollViewAnimation
{

    if (_headerView.pageControl.currentPage==1) {
        _headerView.pageControl.currentPage=0;
    }
    else
    {
        _headerView.pageControl.currentPage++;
    }
     _headerView.scrollView.contentOffset = CGPointMake(_headerView.pageControl.currentPage*screen_width, 0);
}
//pageControl的点击事件
-(void)changePicture
{
    _headerView.scrollView.contentOffset = CGPointMake(_headerView.pageControl.currentPage*screen_width, 0);

    
}
//scrollView的代理
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{

    _headerView.pageControl.currentPage = scrollView.contentOffset.x/screen_width;
    
}
//设置头视图的大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    CGSize size={screen_width,120};
    return size;
}
//返回头视图
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    
   
       _headerView = [self.collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath];
    _headerView.backgroundColor = [UIColor clearColor];
    
        return _headerView;
   
    
}

//返回items
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{

    return self.dataArr.count;
    
}



- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{

    MQSocietyBodyList * model =self.dataArr[indexPath.item];
    MQSocietyViewCell * cell = [self.collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    [cell configCellWithModel:model];
    cell.backgroundColor = [UIColor clearColor];
    return cell;
    
}


-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{

    if ([self isConnectionAvailable]) {
        MQSocietyBodyList * model = self.dataArr[indexPath.item];
        MQVideoSocietyDetailViewController * detailVC = [[MQVideoSocietyDetailViewController alloc]init];
        detailVC.guid = model.bodyModel.memberItem.guid;
        [self presentViewController:detailVC animated:YES completion:nil];

    }
    
    

}


-(void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath
{

    
    if (self.dataArr.count-1==indexPath.item) {
       self.collectionView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
           
           if ([self isConnectionAvailable]) {
               MQSocietyBodyList * model = self.dataArr[indexPath.item];
               self.positionId =[NSMutableString stringWithFormat:@"%@",model.bodyModel.ID];
               [self requestData];
           }
           else
           {
               [self remindOfConnection];
               [self.collectionView.footer endRefreshing];
           }
           
          
       }];
    }
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
